package com.xh.nci;

import java.io.UnsupportedEncodingException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

/**
 * 非ssl方式获取域的组织成员信息
 */
public class AdTest {

    /**
     * 域：test.jd.com user:hhx password:12345678 域控服务器ip:10.0.6.151
     *
     * @param name
     * @return
     * @throws UnsupportedEncodingException
     */
    public String GetADInfo(String name) throws UnsupportedEncodingException {
        String userName = name; // 用户名称
        if (userName == null) {
            userName = "";
        }
        Object company = "";
        String host = "117.79.147.162"; // AD服务器
        String port = "389"; // 端口
        String url = new String("ldap://" + host + ":" + port);

        Hashtable HashEnv = new Hashtable();
        String adminName = "khdev\\administrator"; // 注意用户名的写法：domain\User
        String adminPassword = "kh@2021"; // 密码
        HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
        HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User
        HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password
        HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
        HashEnv.put(Context.PROVIDER_URL, url);
        try {
            LdapContext ctx = new InitialLdapContext(HashEnv, null);
            // 域节点
            String searchBase = "DC=khdev,DC=com";
            // LDAP搜索过滤器类
            String searchFilter = "objectClass=User";
            // 搜索控制器
            SearchControls searchCtls = new SearchControls(); // Create the
            // search
            // controls
            // 创建搜索控制器
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            String returnedAtts[] = {"objectSid", "objectGUID"};

            searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
            // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
            NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);// Search for objects using the filter
            // 初始化搜索结果数为0
            int totalResults = 0;// Specify the attributes to return
            int rows = 0;
            while (answer.hasMoreElements()) {// 遍历结果集
                SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN
                System.out.println("***" + ++rows + "***");
                String dn = sr.getName();
                String match = dn.split("CN=")[1].split(",")[0];// 返回格式一般是CN=ptyh,OU=专卖
                System.out.println("用户名：" + match);

                Attributes Attrs = sr.getAttributes();// 得到符合条件的属性集
                if (Attrs != null) {
                    try {
                        for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore(); ) {
                            Attribute Attr = (Attribute) ne.next();// 得到下一个属性
                            System.out.println("属性名：" + Attr.getID().toString());
                            if ("objectGUID".equals(Attr.getID()) || "objectSid".equals(Attr.getID())) {
                                String st = getGUID(Attr.get().toString().getBytes());

                                System.out.println("属性值：" + st);

                            }
                        }
                    } catch (NamingException e) {
                        System.err.println("Throw Exception : " + e);
                    }
                }
            }
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
            System.err.println("Throw Exception : " + e);
        }
        return company.toString();
    }

    private static String getGUID(byte[] inArr) {
        StringBuffer guid = new StringBuffer();
        for (int i = 0; i < inArr.length; i++) {
            StringBuffer dblByte = new StringBuffer(Integer.toHexString(inArr[i] & 0xff));
            if (dblByte.length() == 1) {
                guid.append("0");
            }
            guid.append(dblByte);
        }
        return guid.toString();
    }

    public static void main(String args[]) throws Exception {
        // 实例化
        AdTest ad = new AdTest();
        String company = ad.GetADInfo("danaad");
    }

}